package com.lt.member;

import inc.CommonFunction;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.hibernate.Session;

import code.lewdy.app.passport.QuestionUtil;
import code.lewdy.app.user.PopularizeLink;
import code.lewdy.db.Database;
import code.lewdy.db.HibernateTemple;
import code.lewdy.db.JdbcUtil;
import code.lewdy.time.TimeHelper;
import code.lewdy.util.DataType;
import code.lewdy.util.FormatUtil;
import code.lewdy.web.PassportUtil;
import code.lewdy.web.request.ExtRequest;
import code.lewdy.web.response.ExtResponse;
import code.lewdy.xml.XMLUtil;

import com.opensymphony.xwork2.ActionSupport;

import dao.Hdao;
import dao.HibernateSessionFactory;

/**
 * uri: /member-?
 * 
 * @author liuding,2012-3-13
 * 
 *         $LastChangedDate$ $Author$
 */
public class MemberAction extends ActionSupport implements
		ServletResponseAware, ServletRequestAware, ApplicationAware {

	JdbcUtil jdbc = new JdbcUtil(Database.TYPE_SQLSERVER);
	String securityPasswordDefault = "123456"; // 默认安全密码
	private Member member;
	private String username;
	private String topName;
	private String password;
	private String securityPassword;
	private String bankName;
	private String bankNo;

	private int uid;
	private int dataId;
	private String ext1;
	private String ext2;
	private CommonFunction fun = new CommonFunction();
	private HttpServletResponse resp;
	private HttpServletRequest req;
	ExtRequest ereq = null;
	private int page;
	private int pageSize;

	/**
	 * 获取今天余下提现次数
	 * 
	 * @return
	 */
	public String getLeftDepositCount() {
		Date date = new Date();
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		String configDate1 = sdf1.format(date);
		String configDate2 = sdf1.format(date);
		MemberConfig mcfg = (MemberConfig) HibernateTemple.load(
				MemberConfig.class, 1);
		configDate1 = configDate1 + " "
				+ TimeHelper.turnSecondToHHMMSS(mcfg.getDepositBeginTime());
		configDate2 = configDate2 + " "
				+ TimeHelper.turnSecondToHHMMSS(mcfg.getDepositEndTime());
		// 时间段内已提现次数
		long depositeCount = (Long) HibernateTemple
				.getUniqueResult("select count(*) from WithdrawRecord where ownerId="
						+ uid
						+ " and CONVERT(varchar(50) , createDate, 120 )<='"
						+ configDate2
						+ "'"
						+ " and CONVERT(varchar(50) , createDate, 120 )>='"
						+ configDate1 + "'");
		long left = mcfg.getDepositMaxCount() - depositeCount;
		ExtResponse.outString(resp, "<data>" + left + "</data>", "xml");
		return null;
	}
	
	/**获取所有会员树统计报表 (不累计下级)
	 */
	public String listAllMemberStatistics() {
		int userId = 0;
		String dateFrom = ext1;
		String dateTo = ext2;
		int begin = (page - 1) * pageSize;
		int end = page * pageSize;
		String msg = "没有查询到数据";
		double subTotal = 0; // 本页小计盈亏
		double total = 0; // 总计盈亏
		double subReturn = 0; // 小计返点
		double totalReturn = 0; // 总计返点
		double subBet = 0; // 小计投注
		double totalBet = 0; // 总计投注
		double subReward = 0; // 小计中奖额
		double totalReward = 0; // 总计中奖额
		double subRecharge = 0; //小计充值
		double totalRecharge = 0; //总计充值
		double subTixian = 0; //小计提现
		double totalTixian = 0; //总计提现
		if (uid > 0) {
			userId = uid;
		}
		Member m = null;
		if (username != null && !username.equals("")) {
			m = (Member) HibernateTemple
					.loadUnique("from Member where username='" + username + "'");
		}
		if (m != null) {
			userId = m.getId();
		}
		List<MemberStatistics> mss = MemberService
				.getStatisticsListByUserId(userId, dateFrom, dateTo);
		int size = mss.size();
		// 总计
		for (MemberStatistics mcs : mss) {
			total += mcs.getTotalWinAmount();
			totalReturn += mcs.getTotalReturnAmount();
			totalBet += mcs.getTotalBetAmount();
			totalReward += mcs.getTotalRewardAmout();
			totalRecharge += mcs.getTotalRecharge();
			totalTixian += mcs.getTotalTixian();
		}
		String listString = "";
		if (begin > size) {
			size = -1; // 页码过大
			msg = "没有查询到数据";
		} else {
			msg = "数据查询已返回";
			end = end > size ? size : end;
			mss = mss.subList(begin, end);
			// 本页小计
			for (MemberStatistics mcs : mss) {
				subTotal += mcs.getTotalWinAmount();
				subBet += mcs.getTotalBetAmount();
				subReturn += mcs.getTotalReturnAmount();
				subReward += mcs.getTotalRewardAmout();
				subRecharge += mcs.getTotalRecharge();
				subTixian += mcs.getTotalTixian();
			}
			size = mss.size();
			listString = XMLUtil.listToXML(mss); // <list>...</list>
		}
		// 保留两位小数
		subTotal = FormatUtil.formatDecimal(subTotal, 2);
		total = FormatUtil.formatDecimal(total, 2);
		subReturn = FormatUtil.formatDecimal(subReturn, 2);
		totalReturn = FormatUtil.formatDecimal(totalReturn, 2);
		subBet = FormatUtil.formatDecimal(subBet, 2);
		totalBet = FormatUtil.formatDecimal(totalBet, 2);
		subReward = FormatUtil.formatDecimal(subReward, 2);
		totalReward = FormatUtil.formatDecimal(totalReward, 2);
		subRecharge = FormatUtil.formatDecimal(subRecharge, 2);
		totalRecharge = FormatUtil.formatDecimal(totalRecharge, 2);
		subTixian = FormatUtil.formatDecimal(subTixian, 2);
		totalTixian = FormatUtil.formatDecimal(totalTixian, 2);
		String respText = "<resp>" + "<size>" + size + "</size>" + "<subTotal>"
				+ subTotal + "</subTotal>" + "<total>" + total + "</total>"
				+ "<subBet>" + subBet + "</subBet>" + "<totalBet>" + totalBet
				+ "</totalBet>" + "<subReturn>" + subReturn + "</subReturn>"
				+ "<totalReturn>" + totalReturn + "</totalReturn>"
				+ "<subReward>" + subReward + "</subReward>" + "<totalReward>"
				+ totalReward + "</totalReward>" + "<msg>" + msg + "</msg>"
				+ "<subRecharge>" + subRecharge + "</subRecharge>" + "<totalRecharge>"+ totalRecharge + "</totalRecharge>" 
				+ "<subTixian>" + subTixian + "</subTixian>" + "<totalTixian>"+ totalTixian + "</totalTixian>" 
				+ "<msg>" + msg + "</msg>"
				+ listString + "</resp>";
		ExtResponse.outString(resp, respText, "xml");
		return null;
	}
	
	/**获取所有会员树统计报表
	 */
	public String listAllMemberTreeStatistics() {
		int userId = 0;
		String dateFrom = ext1;
		String dateTo = ext2;
		int begin = (page - 1) * pageSize;
		int end = page * pageSize;
		String msg = "没有查询到数据";
		double subTotal = 0; // 本页小计盈亏
		double total = 0; // 总计盈亏
		double subReturn = 0; // 小计返点
		double totalReturn = 0; // 总计返点
		double subBet = 0; // 小计投注
		double totalBet = 0; // 总计投注
		double subReward = 0; // 小计中奖额
		double totalReward = 0; // 总计中奖额
		double subRecharge = 0; //小计充值
		double totalRecharge = 0; //总计充值
		double subTixian = 0; //小计提现
		double totalTixian = 0; //总计提现
		if (uid > 0) {
			userId = uid;
		}
		Member m = null;
		if (username != null && !username.equals("")) {
			m = (Member) HibernateTemple
					.loadUnique("from Member where username='" + username + "'");
		}
		if (m != null) {
			userId = m.getId();
		}
		List<MemberStatistics> mss = MemberService
				.getLowerTreeStatisticsListByUserId(userId, dateFrom, dateTo);
		int size = mss.size();
		// 总计
		for (MemberStatistics mcs : mss) {
			total += mcs.getTotalWinAmount();
			totalReturn += mcs.getTotalReturnAmount();
			totalBet += mcs.getTotalBetAmount();
			totalReward += mcs.getTotalRewardAmout();
			totalRecharge += mcs.getTotalRecharge();
			totalTixian += mcs.getTotalTixian();
		}
		String listString = "";
		if (begin > size) {
			size = -1; // 页码过大
			msg = "没有查询到数据";
		} else {
			msg = "数据查询已返回";
			end = end > size ? size : end;
			mss = mss.subList(begin, end);
			// 本页小计
			for (MemberStatistics mcs : mss) {
				subTotal += mcs.getTotalWinAmount();
				subBet += mcs.getTotalBetAmount();
				subReturn += mcs.getTotalReturnAmount();
				subReward += mcs.getTotalRewardAmout();
				subRecharge += mcs.getTotalRecharge();
				subTixian += mcs.getTotalTixian();
			}
			size = mss.size();
			listString = XMLUtil.listToXML(mss); // <list>...</list>
		}
		// 保留两位小数
		subTotal = FormatUtil.formatDecimal(subTotal, 2);
		total = FormatUtil.formatDecimal(total, 2);
		subReturn = FormatUtil.formatDecimal(subReturn, 2);
		totalReturn = FormatUtil.formatDecimal(totalReturn, 2);
		subBet = FormatUtil.formatDecimal(subBet, 2);
		totalBet = FormatUtil.formatDecimal(totalBet, 2);
		subReward = FormatUtil.formatDecimal(subReward, 2);
		totalReward = FormatUtil.formatDecimal(totalReward, 2);
		subRecharge = FormatUtil.formatDecimal(subRecharge, 2);
		totalRecharge = FormatUtil.formatDecimal(totalRecharge, 2);
		subTixian = FormatUtil.formatDecimal(subTixian, 2);
		totalTixian = FormatUtil.formatDecimal(totalTixian, 2);
		String respText = "<resp>" + "<size>" + size + "</size>" + "<subTotal>"
				+ subTotal + "</subTotal>" + "<total>" + total + "</total>"
				+ "<subBet>" + subBet + "</subBet>" + "<totalBet>" + totalBet
				+ "</totalBet>" + "<subReturn>" + subReturn + "</subReturn>"
				+ "<totalReturn>" + totalReturn + "</totalReturn>"
				+ "<subReward>" + subReward + "</subReward>" + "<totalReward>"
				+ totalReward + "</totalReward>" + "<msg>" + msg + "</msg>"
				+ "<subRecharge>" + subRecharge + "</subRecharge>" + "<totalRecharge>"+ totalRecharge + "</totalRecharge>" 
				+ "<subTixian>" + subTixian + "</subTixian>" + "<totalTixian>"+ totalTixian + "</totalTixian>" 
				+ "<msg>" + msg + "</msg>"
				+ listString + "</resp>";
		ExtResponse.outString(resp, respText, "xml");
		return null;
	}

	/**
	 * 获取下级树统计报表
	 * 
	 * @return
	 */
	public String searchLowerTreeStatisticsByUser() {
		String dateFrom = ext1;
		String dateTo = ext2;
		int begin = (page - 1) * pageSize;
		int end = page * pageSize;
		String msg = "没有查询到数据";
		double subTotal = 0; // 本页小计盈亏
		double total = 0; // 总计盈亏
		double subReturn = 0; // 小计返点
		double totalReturn = 0; // 总计返点
		double subBet = 0; // 小计投注
		double totalBet = 0; // 总计投注
		double subReward = 0; // 小计中奖额
		double totalReward = 0; // 总计中奖额
		double subRecharge = 0; //小计充值
		double totalRecharge = 0; //总计充值
		double subTixian = 0; //小计提现
		double totalTixian = 0; //总计提现
		
		Member m = null;
		if (username != null && !username.equals("")) {
			m = (Member) HibernateTemple
					.loadUnique("from Member where username='" + username + "'");
		} else {
			m = (Member) HibernateTemple.load(Member.class, uid);
		}
		List<MemberStatistics> mss = MemberService
				.getLowerTreeStatisticsListByUserId(m.getId(), dateFrom, dateTo);
		int size = mss.size();
		// 总计
		for (MemberStatistics mcs : mss) {
			total += mcs.getTotalWinAmount();
			totalReturn += mcs.getTotalReturnAmount();
			totalBet += mcs.getTotalBetAmount();
			totalReward += mcs.getTotalRewardAmout();
			totalRecharge += mcs.getTotalRecharge();
			totalTixian += mcs.getTotalTixian();
		}
		String listString = "";
		if (begin > size) {
			size = -1; // 页码过大
			msg = "没有查询到数据大";
		} else {
			msg = "数据查询已返回";
			end = end > size ? size : end;
			mss = mss.subList(begin, end);
			// 本页小计
			for (MemberStatistics mcs : mss) {
				subTotal += mcs.getTotalWinAmount();
				subBet += mcs.getTotalBetAmount();
				subReturn += mcs.getTotalReturnAmount();
				subReward += mcs.getTotalRewardAmout();
				subRecharge += mcs.getTotalRecharge();
				subTixian += mcs.getTotalTixian();
			}
			size = mss.size();
			listString = XMLUtil.listToXML(mss); // <list>...</list>
		}
		// 保留两位小数
		subTotal = FormatUtil.formatDecimal(subTotal, 2);
		total = FormatUtil.formatDecimal(total, 2);
		subReturn = FormatUtil.formatDecimal(subReturn, 2);
		totalReturn = FormatUtil.formatDecimal(totalReturn, 2);
		subBet = FormatUtil.formatDecimal(subBet, 2);
		totalBet = FormatUtil.formatDecimal(totalBet, 2);
		subReward = FormatUtil.formatDecimal(subReward, 2);
		totalReward = FormatUtil.formatDecimal(totalReward, 2);
		subRecharge = FormatUtil.formatDecimal(subRecharge, 2);
		totalRecharge = FormatUtil.formatDecimal(totalRecharge, 2);
		subTixian = FormatUtil.formatDecimal(subTixian, 2);
		totalTixian = FormatUtil.formatDecimal(totalTixian, 2);
		String respText = "<resp>" + "<size>" + size + "</size>" + "<subTotal>"
				+ subTotal + "</subTotal>" + "<total>" + total + "</total>"
				+ "<subBet>" + subBet + "</subBet>" + "<totalBet>" + totalBet
				+ "</totalBet>" + "<subReturn>" + subReturn + "</subReturn>"
				+ "<totalReturn>" + totalReturn + "</totalReturn>"
				+ "<subReward>" + subReward + "</subReward>" + "<totalReward>"+ totalReward + "</totalReward>" 
				+ "<subRecharge>" + subRecharge + "</subRecharge>" + "<totalRecharge>"+ totalRecharge + "</totalRecharge>" 
				+ "<subTixian>" + subTixian + "</subTixian>" + "<totalTixian>"+ totalTixian + "</totalTixian>" 
				+ "<msg>" + msg + "</msg>"
				+ listString + "</resp>";
		System.out.println(respText);
		ExtResponse.outString(resp, respText, "xml");
		return null;
	}

	/**
	 * 直接修改登录密码
	 * 
	 * @return
	 */
	public String resetPasswordDirectly() {
		Member m = (Member) HibernateTemple.load(Member.class, member.getId());
		m.setPassword(fun.encryptPassword(member.getPassword()));
		HibernateTemple.update(m);
		return null;
	}

	/**
	 * 验证密保问题
	 * 
	 * @return
	 */
	public String verifyAnswersByMember() {
		Member m = (Member) HibernateTemple.load(Member.class, member.getId());
		if (m == null) {
			ExtResponse.error(resp, "该用户不存在!", "xml");
			return null;
		}
		if (member.getAnswer1().equals(m.getAnswer1())
				&& member.getAnswer2().equals(m.getAnswer2())
				&& member.getAnswer3().equals(m.getAnswer3())) {
			ExtResponse.ok(resp, "验证成功!", "xml");
			return null;
		} else {
			ExtResponse.error(resp, "问题答案验证失败!", "xml");
			return null;
		}
	}

	/**
	 * 通过用户名获取密保问题
	 * 
	 * @return
	 */
	public String gerVerifyQuestionsByName() {
		Member m = (Member) HibernateTemple
				.getUniqueResult("from Member where username=" + " '"
						+ username + "'");
		if (m == null) {
			ExtResponse.error(resp, "用户名不存在！", "xml");
			return null;
		}
		if (m.getQuestionId1() == 0 && m.getQuestionId2() == 0) {
			ExtResponse.error(resp, "您没有设置密保问题，请联系管理员！", "xml");
			return null;
		}
		String q1 = QuestionUtil.getQuestion(m.getQuestionId1());
		String q2 = QuestionUtil.getQuestion(m.getQuestionId2());
		String q3 = QuestionUtil.getQuestion(m.getQuestionId3());
		String data = "<resp>" + "<results>1</results>" + "<userId>"
				+ m.getId() + "</userId>" + "<q1>" + q1 + "</q1>" + "<q2>" + q2
				+ "</q2>" + "<q3>" + q3 + "</q3>" + "</resp>";
		ExtResponse.ok(resp, data, "xml");
		return null;
	}

	/**
	 * 添加会员
	 * 
	 * @return
	 */
	public String addMember() {
		if (MemberService.checkUsername(member.getUsername())) {
			ExtResponse.error(resp, "添加失败:该用户名已存在!", "xml");
			return null;
		}
		member.setPassword(fun.encryptPassword(member.getPassword()));
		member
				.setSecurityPassword(fun
						.encryptPassword(securityPasswordDefault));
		member.setRegisterDate(new Date());
		// 设置默认安全密码
		member.setSecurityPassword(member.getSecurityPassword() == null ? fun
				.encryptPassword(securityPasswordDefault) : member
				.getSecurityPassword());
		int uid = Integer.parseInt("" + HibernateTemple.save(member));
		ExtResponse.ok(resp, "添加成功!", "xml");
		return null;
	}

	/**
	 * 获取会员层级
	 * 
	 * @return
	 */
	public String getLevelCount() {
		int level = MemberService.getLevelCount(uid);
		ExtResponse.outString(resp, "<data>" + level + "</data>", "xml");
		return null;
	}

	/**
	 * 获取前台最高返点
	 * 
	 * @return
	 */
	public String getMaxFrontReturnPoint() {
		// int level = MemberService.getLevelCount(uid);
		double maxPoint = 8;
		double base = 6;
		MemberConfig mcfg = (MemberConfig) HibernateTemple.load(
				MemberConfig.class, 1);
		if (mcfg != null) {
			maxPoint = mcfg.getMaxFrontReturnPoint();
			// maxPoint = maxPoint - level*mcfg.getTopReturnDistance();
			base = mcfg.getReturnPointBase();
		}
		ExtResponse.outString(resp, "<resp><data>" + maxPoint + "</data><base>"
				+ base + "</base>" + "<cha>" + mcfg.getTopReturnDistance()
				+ "</cha>" + "</resp>", "xml");
		return null;
	}

	/**
	 * 更新账户银行信息
	 * 
	 * @return
	 */
	public String updateBankInfo() {
		Member m = (Member) HibernateTemple.load(Member.class, member.getId());
		if ((Long) HibernateTemple
				.getUniqueResult("select count(*) from Member where bankNo='"
						+ member.getBankNo() + "' and id<>"+member.getId()) > 0) {
			ExtResponse.error(resp, "绑定卡号和已有会员重复!", "xml");
			return null;
		}
		m.setBankName(member.getBankName());
		m.setBankNo(member.getBankNo());
		m.setBankAccountName(member.getBankAccountName());
		m.setIsDatumLock(member.getIsDatumLock());
		HibernateTemple.update(m);
		ExtResponse.ok(resp, "绑定卡号成功!", "xml");
		return null;
	}

	/**
	 * 更改验证问题
	 * 
	 * @return
	 */
	public String updateVerifyQuestion() {
		if (member == null) {
			System.out
					.println("updateSecurityQuestion()=>Param member is NULL!");
			return null;
		}
		Member m = (Member) HibernateTemple.load(Member.class, member.getId());
		if (m == null) {
			System.out
					.println("MemberAciton.updatePassword()=>Member is NULL!");
			return null;
		}
		m.setQuestionId1(member.getQuestionId1());
		m.setQuestionId2(member.getQuestionId2());
		m.setQuestionId3(member.getQuestionId3());
		m.setAnswer1(member.getAnswer1());
		m.setAnswer2(member.getAnswer2());
		m.setAnswer3(member.getAnswer3());
		HibernateTemple.update(m);
		return null;
	}

	/**
	 * 会员自己修改密码
	 * 
	 * @return
	 */
	public String updatePassword() {
		String msg = "密码修改成功！";
		boolean success = false;
		if (member == null) {
			System.out.println("updatePassword()=>Param member is NULL!");
			return null;
		}
		Member m = (Member) HibernateTemple.load(Member.class, member.getId());
		if (m == null) {
			System.out
					.println("MemberAciton.updatePassword()=>Member is NULL!");
			return null;
		}
		// ext1为原密码
		if (m.getPassword().equals(fun.encryptPassword(ext1))) {
			m.setPassword(fun.encryptPassword(member.getPassword()));
			HibernateTemple.update(m);
			success = true;
			msg = "密码修改成功！";
		} else {
			success = false;
			msg = "原密码验证错误！";
		}
		if (success) {
			ExtResponse.ok(resp, msg, DataType.XML);
		} else {
			ExtResponse.error(resp, msg, DataType.XML);
		}
		return null;
	}

	/**
	 * 修改资金密码
	 * 
	 * @return
	 */
	public String updateSecurityPassword() {
		String msg = "密码修改成功！";
		Member m = (Member) HibernateTemple.load(Member.class, member.getId());
		if (m == null) {
			System.out
					.println("MemberAciton.updatePassword()=>Member is NULL!");
			return null;
		}
		// ext1为原密码
		if (m.getSecurityPassword() == null) {
			m.setSecurityPassword(fun.encryptPassword(member
					.getSecurityPassword()));
		} else {
			if (m.getSecurityPassword().equals(fun.encryptPassword(ext1))) {
				m.setSecurityPassword(fun.encryptPassword(member
						.getSecurityPassword()));
				HibernateTemple.update(m);
			} else {
				ExtResponse.error(resp, "原密码验证错误！", DataType.XML);
				return null;
			}
		}
		ExtResponse.ok(resp, "密码修改成功！", DataType.XML);
		return null;
	}

	/**
	 * 获取密保问题列表
	 * 
	 * @return
	 */
	public String getVerifyQuestions() {
		ExtResponse.outDataList(resp, QuestionUtil.getQuestions(), "xml");
		return null;
	}

	/**
	 * 是否登录
	 * 
	 * @return
	 * @author liuding,2012-4-27
	 */
	public String isLogin() {
		int success = -1;
		String results = fun.xmlAppend(null, null, "resp", null);
		int sessionUid = PassportUtil.getUserId(req);
		Member m = (Member) HibernateTemple.load(Member.class, sessionUid);
		if (m != null) {
			success = 1;
		} else {
			success = -1;
		}
		// int success = PassportUtil.isLogin(req) == true ? 1 : -1;
		results = fun.xmlAppend(results, "resp", "success", success);
		results = fun.xmlAppend(results, "resp", "userId", PassportUtil
				.getUserId(req));
		results = fun.xmlAppend(results, "resp", "username", PassportUtil
				.getUserName(req));
		fun.ajaxPrint(resp, "xml", null, results);
		return null;
	}

	private Member loadMember() {
		Member m = new Member();
		m.setPassword(fun.encryptPassword(password));
		m.setSecurityPassword(securityPassword != null ? fun
				.encryptPassword(securityPassword) : "");
		m.setBankName(bankName != null ? bankName : "");
		m.setBankNo(bankNo != null ? bankNo : "");
		m.setRegisterDate(new Date());
		m.setBdReturnPoint(ereq.getFloat("bdReturnPoint"));
		return m;
	}

	/**
	 * 自助注册（通过推广链接注册）
	 * 
	 * @return
	 */
	public String myRegister() {
		if (req.getSession().getAttribute("topUid") != null) {
			int fatherId = (Integer) req.getSession().getAttribute("topUid");
			member.setFatherId(fatherId);
			member.setTopName((String) HibernateTemple
					.getUniqueResult("select username from Member where id="
							+ fatherId));
		}
		member.setPassword(fun.encryptPassword(member.getPassword()));
		member.setSecurityPassword(fun.encryptPassword(member
				.getSecurityPassword()));
		if (MemberService.checkUsername(member.getUsername())) {
			ExtResponse.error(resp, "该用户名已存在!", "xml");
			return null;
		}
		if (member.getUsername() == null) {
			ExtResponse.error(resp, "用户名不能为空!", "xml");
			return null;
		}
		// 设置默认安全密码
		member.setSecurityPassword(member.getSecurityPassword() == null ? fun
				.encryptPassword(securityPasswordDefault) : member
				.getSecurityPassword());
		int uid = Integer.parseInt("" + HibernateTemple.save(member));

		if (uid <= 0) {
			ExtResponse.error(resp, "注册失败：该用户已存在！", "xml");
			return null;
		}
		// 生成推广链接
		PopularizeLink link = new PopularizeLink();
		link.setOwnerId(uid);
		link.setUrlParamsString(PopularizeLink.produceParamsString(uid));
		HibernateTemple.save(link);
		ExtResponse.ok(resp, "注册成功！", "xml");
		return null;
	}

	/**
	 * 获取上级信息
	 * 
	 * @return
	 */
	public String getTopInfo() {
		if (req.getSession().getAttribute("topUid") != null) {
			int topUid = (Integer) req.getSession().getAttribute("topUid");
		}
		String topUsername = req.getSession().getAttribute("topUsername") != null ? (String) req
				.getSession().getAttribute("topUsername")
				: "";
		ExtResponse.outString(resp, "<topUsername>" + topUsername
				+ "</topUsername>", DataType.XML);
		return null;
	}

	// 注册
	public String register() {
		if (ereq.getString("regTop") != null) {
			String linkStr = ereq.getString("regTop");
			if (!linkStr.startsWith("regTop=")) {
				linkStr = "regTop=" + linkStr;
			}
			req.getSession().setAttribute("regTop", linkStr);
			int topUid = Integer.parseInt(""
					+ PopularizeLink.getOwnerIdFromURL(linkStr));
			Member tm = (Member) HibernateTemple.load(Member.class, topUid);
			if (tm != null) {
				req.getSession().setAttribute("topUid", tm.getId());
				req.getSession().setAttribute("topUsername", tm.getUsername());
			}
			String basePath = req.getScheme() + "://" + req.getServerName()
					+ ":" + req.getServerPort() + req.getContextPath() + "/";
			try {
				resp.sendRedirect(basePath + "bin/Register.html");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
			// return "register";
		}
		System.out.println("Register...");
		if (ereq.getString("username") == null)
			return null;
		boolean isAddByHand = ereq.getString("addByHand") != null ? true
				: false;
		String results = fun.xmlAppend(null, null, "resp", null);
		member = loadMember();
		if (MemberService.checkUsername(member.getUsername())) {
			ExtResponse.error(resp, "该用户名已存在!", "xml");
			return null;
		}
		// 建立账户统计记录
		MemberStatistics msnew = new MemberStatistics();
		if (isAddByHand) {
			member.setFatherId(ereq.getInt("fatherId"));
			member.setTopName(topName);
			member.setUsername(username);
			// 检查用户名
			if (MemberService.checkUsername(member.getUsername())) {
				ExtResponse.error(resp, "添加失败:该用户名已存在!", "xml");
				return null;
			}

			member.setAccountType(ereq.getInt("accountType"));
			member.setReturnPoint(ereq.getFloat("returnPoint"));
			/*
			 * msnew.setFatherId(member.getFatherId()); MemberStatistics mts =
			 * (MemberStatistics)
			 * jdbc.getEntityBySQL(MemberStatistics.class.getName(),
			 * "where ownerId="+member.getFatherId());
			 * mts.setLowerMemberCount(mts.getLowerMemberCount()+1);
			 * 
			 * HibernateTemple.update(mts);
			 */
		}

		if (member.getUsername() == null) {
			ExtResponse.error(resp, "用户名不能为空!", "xml");
			return null;
		}
		// 设置默认安全密码
		member.setSecurityPassword((member.getSecurityPassword() == null || ""
				.equals(member.getSecurityPassword())) ? fun
				.encryptPassword(securityPasswordDefault) : member
				.getSecurityPassword());
		int uid = Integer.parseInt("" + HibernateTemple.save(member));
		msnew.setOwnerId(uid);
		msnew.setOwnerName(member.getUsername());
		HibernateTemple.save(msnew);
		if (uid > 0) {
			results = fun.xmlAppend(results, "resp", "success", 1);
			// 生成推广链接
			PopularizeLink link = new PopularizeLink();
			link.setOwnerId(uid);
			link.setUrlParamsString(PopularizeLink.produceParamsString(uid));
			Hdao.save(link);
		} else {
			results = fun.xmlAppend(results, "resp", "success", 0);
		}
		if (isAddByHand) {
			System.out.println("Register=>手动添加会员！");
		} else {
			System.out.println("Register=>自助注册会员！");
			PassportUtil.login(req, uid, username);
		}
		fun.ajaxPrint(resp, "xml", null, results);
		System.out.println("register():" + results);
		return null;
	}

	// 登录
	public String login() {
		String results = fun.xmlAppend(null, null, "resp", null);
		long size = (Long)HibernateTemple
			.getUniqueResult("select count(*) from Member where " +
					" username='"+username+"' and password='"+fun.encryptPassword(password)+"'");
		
		if (size > 0) {
			Member m = (Member)HibernateTemple
				.getUniqueResult("from Member where username='"+username+"'");
			if (m.getIsLock() == 1) {
				results = fun.xmlAppend(results, "resp", "success", -2); // 登录失败：账户已锁定
			} else {
				m.setLastLoginDate(new Date());
				HibernateTemple.update(m);
				results = fun.xmlAppend(results, "resp", "success", 1);
				results = fun.xmlAppend(results, "resp", "accoutType", m
						.getAccountType());
				PassportUtil.login(req, m.getId(), m.getUsername());
				MemberService.setLoginFlag(m.getId());
			}
		} else {
			results = fun.xmlAppend(results, "resp", "success", 0);
		}
		results = fun.ajaxPrint(resp, "xml", null, results);
		System.out.println("login():" + results);
		return null;
	}

	/**
	 * 退出登录
	 * 
	 * @return
	 * @author liuding,2012-4-25
	 */
	public String logout() {
		PassportUtil.logout(req);
		return null;
	}

	public String logout2() {
		PassportUtil.logout(req);
		return null;
	}

	// 踢会员下线
	public String offLine() {
		MemberService.setLogoutFlag(uid);
		return null;
	}

	public String deleteMember() {
		Session s = HibernateSessionFactory.getSession();
		s.beginTransaction();
		Member m = (Member) s.get(Member.class, uid);
		s.getTransaction().commit();
		if (m != null) {
			s.beginTransaction();
			s.delete(m);
			s.getTransaction().commit();
		}
		return null;
	}

	public String updateMember() {

		return null;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public void setServletResponse(HttpServletResponse resp) {
		// TODO Auto-generated method stub
		this.resp = resp;
	}

	public int getUid() {
		return uid;
	}

	public void setUid(int uid) {
		this.uid = uid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSecurityPassword() {
		return securityPassword;
	}

	public void setSecurityPassword(String securityPassword) {
		this.securityPassword = securityPassword;
	}

	public String getBankName() {
		return bankName;
	}

	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	public String getBankNo() {
		return bankNo;
	}

	public void setBankNo(String bankNo) {
		this.bankNo = bankNo;
	}

	public void setServletRequest(HttpServletRequest req) {
		// TODO Auto-generated method stub
		this.req = req;
		ereq = new ExtRequest(this.req);
	}

	public void setTopName(String topName) {
		this.topName = topName;
	}

	public String getTopName() {
		return topName;
	}

	public void setDataId(int dataId) {
		this.dataId = dataId;
	}

	public int getDataId() {
		return dataId;
	}

	public void setExt1(String ext1) {
		this.ext1 = ext1;
	}

	public String getExt1() {
		return ext1;
	}

	public void setExt2(String ext2) {
		this.ext2 = ext2;
	}

	public String getExt2() {
		return ext2;
	}

	public void setApplication(Map<String, Object> arg0) {
		// TODO Auto-generated method stub

	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPage() {
		return page;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageSize() {
		return pageSize;
	}

}
